package com.itheima.health.controller;


import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/mobile/login")
@Slf4j
public class MobileLoginController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberService memberService;

    /**
     * 登录设置
     * @param param
     * @param request
     * @return
     */
    @PostMapping("/smsLogin")
    public Result smsLogin(@RequestBody Map param, HttpServletRequest request){
        //验证码校验
        String  telephone = param.get("telephone").toString();
        String  validateCode = param.get("validateCode").toString();
        //找键 因为此业务是移动端登录业务 所以 type就是  MOBILE_SIGNIN
        String redisKey = RedisConst.VALIDATE_CODE_PREFIX +"_MOBILE_SIGNIN_"+telephone;
        //从redis 获取  验证码
        String code = redisTemplate.opsForValue().get(redisKey).toString();
        if (!StringUtils.isEmpty(code)&& code.equals(validateCode)) {
            //如果匹配就删除 redis 并返回true
            redisTemplate.delete(redisKey);
            //创建会员
            Member member = new Member();
            member.setFileNumber(telephone);
            member = memberService.createOrUpdate(member);
            request.getSession().setAttribute("member",member);
            log.info("[登录成功]>>>>{}",member.getId());
            return new Result(true, MessageConst.LOGIN_SUCCESS);
        }else {
            return new Result(false,MessageConst.LOGIN_FAIL);
        }
    }
}
